"""Utility functions for the solver"""

from numpy import load as l
from hogs.grids import grid1d as grid
import os
import sys

HAS_PBAR = True
try:
    import progressbar
except ImportError:
    HAS_PBAR = False

def load(fname):
    """Load saved data"""
    data = l(fname)
    
    q = data["q"]; w = data["w"];
    xc = data["xc"]; x = data["x"]
    t = data["t"]

    g = grid.Grid1D()

    g.x = x; g.xc = xc
    g.q = q; g.w = w

    g.ncells = len(xc); g.nnodes = len(x)
    g._setup_cells(nvar=len(q))

    g.time = t

    return g

################################################################################
# `PBar` class.
############################################################################### 
class PBar(object):
    """A simple wrapper around the progressbar so it works if a user has
    it installed or not.
    """
    def __init__(self, maxval, show=True):
        bar = None
        self.count = 0
        self.maxval = maxval
        self.show = show 
        if HAS_PBAR and show:
            widgets = [progressbar.Percentage(), ' ', progressbar.Bar(),
                       progressbar.ETA()]
            bar = progressbar.ProgressBar(widgets=widgets,
                                          maxval=maxval).start()
        self.bar = bar

    def update(self, percentage_done):
        self.count += 1
        if self.bar is not None:
            self.bar.update( percentage_done )
        elif self.show:
            sys.stderr.write('\r%d%%'%int(self.count*100/self.maxval))
            sys.stderr.flush()

    def finish(self):
        if self.bar is not None:
            self.bar.finish()
        elif self.show:
            sys.stderr.write('\r100%\n')

            sys.stderr.flush()

##############################################################################
# friendly mkdir  from http://code.activestate.com/recipes/82465/.
############################################################################## 
def mkdir(newdir):
    """works the way a good mkdir should :)
        - already exists, silently complete
        - regular file in the way, raise an exception
        - parent directory(ies) does not exist, make them as well
    """
    if os.path.isdir(newdir):
        pass

    elif os.path.isfile(newdir):
        raise OSError("a file with the same name as the desired " \
                      "dir, '%s', already exists." % newdir)

    else:
        head, tail = os.path.split(newdir)

        if head and not os.path.isdir(head):
            mkdir(head)

        if tail:
            try:
                os.mkdir(newdir)
            # To prevent race in mpi runs
            except OSError as e:
                import errno
                if e.errno == errno.EEXIST and os.path.isdir(newdir):
                    pass
                else:
                    raise

################################################################################
# `PBar` class.
############################################################################### 
# class PBar(object):
#     """A simple wrapper around the progressbar so it works if a user has
#     it installed or not.
#     """
#     def __init__(self, maxval, show=True):
#         bar = None
#         self.count = 0
#         self.maxval = maxval
#         self.show = show 
#         self.bar = bar

#     def update(self):
#         self.count += 1
#         sys.stderr.write('\r%d%%'%int(self.count*100/self.maxval))
#         sys.stderr.flush()

#     def finish(self):
#         sys.stderr.write('\r100%\n')
#         sys.stderr.flush()
